package org.darcy.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.reflect.FieldUtils;
import org.darcy.entity.privilege.SysUser;
import org.darcy.framework.constant.SysConstant;
import org.darcy.framework.generic.GenericService;
import org.darcy.framework.model.R;
import org.darcy.utils.common.ReturnCode;
import org.darcy.utils.vo.ReturnVo;
import org.darcy.vo.CheckExistVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;

public abstract class BaseController<T> {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	protected static final String EXIST_MESSAGE = "不能重复！";

	/**
	 * 获取登录用户
	 *
	 * @return
	 */
	protected SysUser getLoginUser() {
		if (StpUtil.isLogin()) {
			Object loginId = StpUtil.getLoginId();
			SaSession session = StpUtil.getSessionByLoginId(loginId);
			Object userObj = session.get(SysConstant.LOGIN_USER);
			if (userObj != null) {
				return (SysUser) userObj;
			}
		}
		return null;
	}

	public void authorizationException(HttpServletResponse response) {
		ReturnVo returnVo = new ReturnVo(ReturnCode.FAIL, "您无此功能权限，请联系超级管理员！");
		writeJson(returnVo, response);
	}

	/**
	 * 输出JSON
	 */
	private void writeJson(ReturnVo returnVo, HttpServletResponse response) {
		PrintWriter out = null;
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json; charset=utf-8");
			out = response.getWriter();
			out.write(JSONUtil.toJsonStr(returnVo));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	/**
	 * 判断字段是否存在
	 */
	protected R checkExist(GenericService<T> service, CheckExistVo checkExistVo) {
		QueryWrapper<T> userQueryWrapper = new QueryWrapper<>();
		String camelToUnderline = com.baomidou.mybatisplus.core.toolkit.StringUtils
				.camelToUnderline(checkExistVo.getField());
		userQueryWrapper.eq(camelToUnderline, checkExistVo.getFieldValue());
		userQueryWrapper.eq("del_flag", SysConstant.DEL_FLAG_1);
		long count = service.count(userQueryWrapper);
		if (StringUtils.isNotBlank(checkExistVo.getId())) {
			T entity = service.getById(checkExistVo.getId());
			try {
				Object fieldValue = FieldUtils.readField(entity, checkExistVo.getField(), true);
				String oldValue = (String) fieldValue;
				if (!oldValue.equals(checkExistVo.getFieldValue()) && count > 0) {
					return R.ok(checkExistVo.getFieldName() + EXIST_MESSAGE).data(false);
				}
			} catch (IllegalAccessException e) {
				logger.error("没有相关的字段！字段为：" + checkExistVo.getField());
			}
		} else {
			if (count > 0) {
				return R.ok(checkExistVo.getFieldName() + EXIST_MESSAGE).data(false);
			}
		}
		return R.ok("OK").data(true);

	}
}
